<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>告警管理 - RustCloud 仪表板</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }

        .header h1 {
            font-size: 28px;
            font-weight: 600;
        }

        .nav {
            background: white;
            padding: 15px 0;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .nav ul {
            list-style: none;
            display: flex;
            gap: 30px;
        }

        .nav a {
            text-decoration: none;
            color: #333;
            font-weight: 500;
            padding: 10px 15px;
            border-radius: 5px;
            transition: background-color 0.3s;
        }

        .nav a:hover, .nav a.active {
            background-color: #667eea;
            color: white;
        }

        .alert-summary {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .summary-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
        }

        .summary-count {
            font-size: 36px;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .summary-label {
            color: #666;
            font-size: 14px;
        }

        .critical { color: #dc2626; }
        .error { color: #ef4444; }
        .warning { color: #f59e0b; }
        .info { color: #3b82f6; }

        .alert-controls {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            display: flex;
            gap: 15px;
            align-items: center;
        }

        .filter-select {
            padding: 8px 12px;
            border: 2px solid #e1e5e9;
            border-radius: 5px;
            background: white;
        }

        .filter-select:focus {
            outline: none;
            border-color: #667eea;
        }

        .refresh-button {
            background: #667eea;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .refresh-button:hover {
            background: #5a67d8;
        }

        .alert-list {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .alert-list h3 {
            background: #f8f9fa;
            padding: 15px 20px;
            margin: 0;
            border-bottom: 1px solid #e1e5e9;
        }

        .alert-item {
            padding: 20px;
            border-bottom: 1px solid #f1f3f4;
            transition: background-color 0.3s;
        }

        .alert-item:hover {
            background-color: #f8f9fa;
        }

        .alert-item:last-child {
            border-bottom: none;
        }

        .alert-header {
            display: flex;
            justify-content: between;
            align-items: center;
            margin-bottom: 10px;
        }

        .alert-name {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 5px;
        }

        .alert-severity {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
            text-transform: uppercase;
        }

        .severity-critical {
            background: #fef2f2;
            color: #dc2626;
            border: 1px solid #fecaca;
        }

        .severity-error {
            background: #fef2f2;
            color: #ef4444;
            border: 1px solid #fecaca;
        }

        .severity-warning {
            background: #fffbeb;
            color: #f59e0b;
            border: 1px solid #fed7aa;
        }

        .severity-info {
            background: #eff6ff;
            color: #3b82f6;
            border: 1px solid #bfdbfe;
        }

        .alert-description {
            color: #666;
            margin-bottom: 10px;
        }

        .alert-time {
            font-size: 12px;
            color: #999;
        }

        .alert-actions {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }

        .action-button {
            padding: 5px 10px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
            transition: background-color 0.3s;
        }

        .action-acknowledge {
            background: #10b981;
            color: white;
        }

        .action-acknowledge:hover {
            background: #059669;
        }

        .action-silence {
            background: #f59e0b;
            color: white;
        }

        .action-silence:hover {
            background: #d97706;
        }

        .action-delete {
            background: #ef4444;
            color: white;
        }

        .action-delete:hover {
            background: #dc2626;
        }

        .no-alerts {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .error-message {
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: #dc2626;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }

        .alert-labels {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin-top: 10px;
        }

        .label-tag {
            background: #e1e5e9;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 11px;
            font-family: monospace;
        }

        .status-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-firing {
            background-color: #ef4444;
        }

        .status-pending {
            background-color: #f59e0b;
        }

        .status-resolved {
            background-color: #10b981;
        }
    </style>
</head>
<body>
    <header class="header">
        <div class="container">
            <h1>🚨 告警管理</h1>
        </div>
    </header>

    <nav class="nav">
        <div class="container">
            <ul>
                <li><a href="/">概览</a></li>
                <li><a href="/metrics">指标</a></li>
                <li><a href="/alerts" class="active">告警</a></li>
                <li><a href="/apm">APM</a></li>
                <li><a href="/health">健康检查</a></li>
            </ul>
        </div>
    </nav>

    <main class="container">
        <!-- 告警统计 -->
        <div class="alert-summary">
            <div class="summary-card">
                <div class="summary-count critical" id="critical-count">-</div>
                <div class="summary-label">严重告警</div>
            </div>
            <div class="summary-card">
                <div class="summary-count error" id="error-count">-</div>
                <div class="summary-label">错误告警</div>
            </div>
            <div class="summary-card">
                <div class="summary-count warning" id="warning-count">-</div>
                <div class="summary-label">警告告警</div>
            </div>
            <div class="summary-card">
                <div class="summary-count info" id="info-count">-</div>
                <div class="summary-label">信息告警</div>
            </div>
        </div>

        <!-- 控制面板 -->
        <div class="alert-controls">
            <label>过滤级别:</label>
            <select class="filter-select" id="severity-filter">
                <option value="">全部</option>
                <option value="Critical">严重</option>
                <option value="Error">错误</option>
                <option value="Warning">警告</option>
                <option value="Info">信息</option>
            </select>

            <label>状态:</label>
            <select class="filter-select" id="status-filter">
                <option value="">全部状态</option>
                <option value="Firing">正在触发</option>
                <option value="Pending">待处理</option>
                <option value="Resolved">已解决</option>
            </select>

            <button class="refresh-button" onclick="loadAlerts()">🔄 刷新</button>
        </div>

        <div id="error-container"></div>

        <!-- 告警列表 -->
        <div class="alert-list">
            <h3>活跃告警列表</h3>
            <div id="alerts-container">
                <div class="loading">正在加载告警...</div>
            </div>
        </div>
    </main>

    <script>
        let allAlerts = [];

        // 加载告警数据
        async function loadAlerts() {
            try {
                showLoading();
                const response = await fetch('/api/alerts');
                const result = await response.json();
                
                if (result.success) {
                    allAlerts = result.data;
                    updateAlertSummary();
                    displayAlerts(allAlerts);
                    hideError();
                } else {
                    showError('获取告警失败: ' + result.error);
                }
            } catch (error) {
                console.error('加载告警失败:', error);
                showError('无法连接到服务器');
            }
        }

        // 更新告警统计
        function updateAlertSummary() {
            const summary = {
                Critical: 0,
                Error: 0,
                Warning: 0,
                Info: 0
            };

            allAlerts.forEach(alert => {
                if (summary[alert.severity] !== undefined) {
                    summary[alert.severity]++;
                }
            });

            document.getElementById('critical-count').textContent = summary.Critical;
            document.getElementById('error-count').textContent = summary.Error;
            document.getElementById('warning-count').textContent = summary.Warning;
            document.getElementById('info-count').textContent = summary.Info;
        }

        // 显示告警列表
        function displayAlerts(alerts) {
            const container = document.getElementById('alerts-container');
            
            if (alerts.length === 0) {
                container.innerHTML = '<div class="no-alerts">✅ 暂无告警</div>';
                return;
            }

            container.innerHTML = alerts.map(alert => {
                const timeAgo = new Date(alert.fired_at).toLocaleString();
                const labels = Object.entries(alert.labels).map(([k, v]) => 
                    `<span class="label-tag">${k}="${v}"</span>`
                ).join('');

                return `
                    <div class="alert-item">
                        <div class="alert-header">
                            <div>
                                <div class="alert-name">
                                    <span class="status-indicator status-${alert.state.toLowerCase()}"></span>
                                    ${alert.name}
                                </div>
                                <span class="alert-severity severity-${alert.severity.toLowerCase()}">
                                    ${alert.severity}
                                </span>
                            </div>
                        </div>
                        <div class="alert-description">
                            ${alert.annotations.description || '无描述'}
                        </div>
                        <div class="alert-time">
                            触发时间: ${timeAgo} | 当前值: ${alert.value} | 阈值: ${alert.threshold}
                        </div>
                        ${labels ? `<div class="alert-labels">${labels}</div>` : ''}
                        <div class="alert-actions">
                            <button class="action-button action-acknowledge" onclick="acknowledgeAlert('${alert.id}')">
                                确认
                            </button>
                            <button class="action-button action-silence" onclick="silenceAlert('${alert.id}')">
                                静音
                            </button>
                            <button class="action-button action-delete" onclick="deleteAlert('${alert.id}')">
                                删除
                            </button>
                        </div>
                    </div>
                `;
            }).join('');
        }

        // 告警操作
        async function acknowledgeAlert(alertId) {
            // TODO: 实现确认告警
            console.log('确认告警:', alertId);
        }

        async function silenceAlert(alertId) {
            // TODO: 实现静音告警
            console.log('静音告警:', alertId);
        }

        async function deleteAlert(alertId) {
            if (!confirm('确定要删除这个告警吗？')) {
                return;
            }

            try {
                const response = await fetch(`/api/alerts/${alertId}`, {
                    method: 'DELETE'
                });
                const result = await response.json();
                
                if (result.success) {
                    loadAlerts(); // 重新加载列表
                } else {
                    showError('删除失败: ' + result.error);
                }
            } catch (error) {
                console.error('删除告警失败:', error);
                showError('删除失败');
            }
        }

        // 过滤功能
        function setupFilters() {
            const severityFilter = document.getElementById('severity-filter');
            const statusFilter = document.getElementById('status-filter');

            function applyFilters() {
                let filtered = allAlerts;

                // 按严重级别过滤
                const selectedSeverity = severityFilter.value;
                if (selectedSeverity) {
                    filtered = filtered.filter(alert => alert.severity === selectedSeverity);
                }

                // 按状态过滤
                const selectedStatus = statusFilter.value;
                if (selectedStatus) {
                    filtered = filtered.filter(alert => alert.state === selectedStatus);
                }

                displayAlerts(filtered);
            }

            severityFilter.addEventListener('change', applyFilters);
            statusFilter.addEventListener('change', applyFilters);
        }

        // 显示加载状态
        function showLoading() {
            document.getElementById('alerts-container').innerHTML = '<div class="loading">正在加载告警...</div>';
        }

        // 显示错误
        function showError(message) {
            const errorContainer = document.getElementById('error-container');
            errorContainer.innerHTML = `<div class="error-message">❌ ${message}</div>`;
        }

        // 隐藏错误
        function hideError() {
            document.getElementById('error-container').innerHTML = '';
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            setupFilters();
            loadAlerts();
            
            // 设置自动刷新（每15秒）
            setInterval(loadAlerts, 15000);
        });
    </script>
</body>
</html>